import { getConfig } from '@config/env'
import type {
  LoginPayload,
  LoginResponse,
  ProfileResponse,
} from '@/types/auth'
import { http } from './http'

const config = getConfig()

const MOCK_USER = {
  id: '1',
  name: '系统管理员',
  email: 'admin@example.com',
  role: 'admin' as const,
}

const simulateRequest = async <T,>(data: T, shouldFail = false): Promise<T> => {
  await new Promise((resolve) => setTimeout(resolve, 800))
  if (shouldFail) {
    throw new Error('模拟接口错误')
  }
  return data
}

const loginMock = async (payload: LoginPayload): Promise<LoginResponse> => {
  const isValid = payload.username === 'admin' && payload.password === '123456'
  if (!isValid) {
    throw new Error('用户名或密码错误')
  }

  return simulateRequest({
    token: 'mock-token-123456',
    user: MOCK_USER,
  })
}

const getProfileMock = async (): Promise<ProfileResponse> => {
  return simulateRequest({ user: MOCK_USER })
}

export const authApi = {
  async login(payload: LoginPayload): Promise<LoginResponse> {
    if (config.enableMock || !config.apiBaseUrl) {
      return loginMock(payload)
    }
    const { data } = await http.post<LoginResponse>('/auth/login', payload)
    return data
  },

  async getProfile(): Promise<ProfileResponse> {
    if (config.enableMock || !config.apiBaseUrl) {
      return getProfileMock()
    }
    const { data } = await http.get<ProfileResponse>('/auth/profile')
    return data
  },
}


